// components/search/index.js
import {
  KeywordModel
} from "keyword.js"
import {
  BookModel
} from "../../models/book.js";
import {
  paginationBev
} from "../behaviors/pagination.js";
const keywordModel = new KeywordModel();
const bookModel = new BookModel();

Component({
  /**
   * 组件的属性列表
   */
  behaviors: [paginationBev],
  properties: {
    more: {
      type: String,
      observer: "loadMore"
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    historyWords: [],
    hotWords: [],
    searching: false,
    q: "",
    loading: false,
    loadingCenter: false,

  },

  attached() {
    const historyWords = keywordModel.getHistory();
    const hotWords = keywordModel.getHot();
    this.setData({
      historyWords
    });

    hotWords.then(res => {
      this.setData({
        hotWords: res.hot
      });
    });
  },

  /**
   * 组件的方法列表
   */
  methods: {
    loadMore() {
      const td = this.data;
      if (!td.q) {
        return;
      }
      if (this.isLocked()) {
        return;
      }

      if (this.hasMore()) {
        this.locked();
        bookModel.search(this.getCurrentStart(), td.q)
          .then(res => {
            this.setMoreData(res.books);
            this.unLocked();
          }, () => {
            this.unLocked();
          });
      }
    },


    // onReachBottom() {
    //   this.setData({
    //     more
    //   });
    // },

    onCancel(e) {
      this.initialize();
      this._showResult();
      this.triggerEvent("cancel", {}, {});
    },

    onDelte(e) {
      this.initialize();
      this._showResult();
      this._closeResult();
    },

    onConfirm(e) {
      this._showResult();
      this._showLoadingCenter();
      this.initialize();
      const word = e.detail.value || e.detail.text;
      this.setData({
        q: word
      });
      bookModel.search(0, word)
        .then(res => {
          this.setMoreData(res.books);
          this.setTotal(res.total);
          keywordModel.addToHistory(word);
          this._hideLoadingCenter();
        });

    },

    _showLoadingCenter() {
      this.setData({
        loadingCenter: true
      });
    },
    _hideLoadingCenter() {
      this.setData({
        loadingCenter: false
      });
    },

    _showResult() {
      this.setData({
        searching: true
      });
    },

    _closeResult() {
      this.setData({
        searching: false,
        q: ""
      });
    },



  }
})